package alogrithm;

import java.util.Random;

/**
 * @author lbw
 * @version 1.0
 * @date 2021/8/17 12:42
 */
public class KthTest {

    Random random = new Random();

    public static void main(String[] args) {
        int[] a = new int[]{1, 4, 5, 6, 3, 7};
        System.out.println(new KthTest().findKthLargest(a, 1));
    }

    private int findKthLargest(int[] nums, int k) {
        return quickSelect(nums, 0, nums.length - 1, nums.length - k);
    }

    private int quickSelect(int[] nums, int l, int r, int index) {
        int q = randomPartition(nums, l, r); // 得到当前元素的位置, 与k比较
        if (q == index) {
            return nums[q];
        }
        if (q < index) {
            return quickSelect(nums, q + 1, r, index);
        } else {
            return quickSelect(nums, l, q - 1, index);
        }
    }

    private int randomPartition(int[] nums, int l, int r) {
        int i = random.nextInt(r - l + 1) + l;
        swap(nums, i, r);
        return partition(nums, l, r);
    }

    private int partition(int[] nums, int l, int r) { // 划分算法, 将<x划分在x的左边, >x划分在x的右边
        int x = nums[r], i = l - 1;
        for (int j = l; j < r; ++j) {
            if (nums[j] <= x) {
                swap(nums, ++i, j);
            }
        }
        swap(nums, i + 1, r);
        return i + 1;
    }


    private void swap(int[] nums, int a, int b) {
        int temp = nums[a];
        nums[a] = nums[b];
        nums[b] = temp;
    }
}
